<template>
  <div class="custom-tree-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新建
      </el-button>
    </div>
    <el-tree
      :data="data"
      node-key="id"
    >
      <span slot-scope="{ node, data }" class="custom-tree-node">
        <span>{{ data.name }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => handleUpdate(data)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="名称" prop="name">
          <el-col :span="12">
            <el-input v-model="temp.name" />
          </el-col>
        </el-form-item>
        <el-form-item label="上级机构">
          <el-select
            ref="selectUpResId"
            v-model="temp.parentId"
            clearable
            placeholder="请选择"
            @clear="resetTemp"
          >
            <el-option key="upResId" hidden :value="temp.parentId" :label="upResName" />
            <el-tree
              :data="data"
              :props="defaultProps"
              :expand-on-click-node="false"
              :check-on-click-node="true"
              @node-click="handleNodeClick"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年级">
          <el-select v-model="temp.gradeId" placeholder="请选择年级">
            <el-option v-for="g in gradeList" :label="g.name" :value="g.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deleteOrg, listGrade, listTreeOrg, patchOrg, postOrg } from '@/api/org'

export default {
  name: 'Org',
  data() {
    return {
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      temp: {
        id: undefined,
        parentId: undefined,
        gradeId: undefined,
        name: ''
      },
      rules: {
        name: { required: true, trigger: 'blur', message: '年级不能为空' }
      },
      upResName: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      gradeList: undefined,
      data: undefined
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      listTreeOrg({ typ: 0 }).then(response => {
        this.data = response.data
      })
      listGrade().then(response => {
        this.gradeList = response.data
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        parentId: undefined,
        name: ''
      }
      this.upResName = ''
    },
    handleNodeClick(data) {
      // 这里主要配置树形组件点击节点后，设置选择器的值；自己配置的数据，仅供参考
      this.upResName = data.name
      this.temp.parentId = data.id
      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.selectUpResId.blur()
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = null
          postOrg(this.temp).then((response) => {
            this.initData()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功!',
              type: 'success',
              duration: 2000
            })
          }).catch(() => {
            this.$message({
              showClose: true,
              message: '添加出错',
              type: 'error'
            })
          })
        }
      })
    },

    handleUpdate(data) {
      this.temp.id = data.id // copy obj
      this.temp.name = data.name
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          patchOrg(tempData).then(() => {
            this.initData()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功!',
              type: 'success',
              duration: 2000
            })
          }).catch(() => {
            this.$message({
              showClose: true,
              message: '更新出错',
              type: 'error'
            })
          })
        }
      })
    },

    remove(node, data) {
      console.log(node)
      console.log(data)
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      deleteOrg({ id: data.id }).then(response => {
        this.$notify({
          title: '成功',
          message: '删除成功!',
          type: 'success',
          duration: 2000
        })
        children.splice(index, 1)
      })
    },

    renderContent(h, { node, data, store }) {
      return (
        <span class='custom-tree-node'>
          <span>{node.label}</span>
          <span>
            <el-button size='mini' type='text' on-click={() => this.append(data)}>Append</el-button>
            <el-button size='mini' type='text' on-click={() => this.remove(node, data)}>Delete</el-button>
          </span>
        </span>)
    },

    loadNode() {
    }
  }
}
</script>

<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
